package dao;

import model.Share;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import utils.DataSourceUtils;

import java.sql.SQLException;
import java.util.List;

/**
 * 商品分享数据访问类
 */
public class ShareDao {
    
    /**
     * 添加分享记录
     * @param share 分享对象
     * @throws SQLException SQL异常
     */
    public void addShare(Share share) throws SQLException {
        QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "insert into share(user_id, goods_id, share_type, share_time, share_ip) values(?, ?, ?, now(), ?)";
        r.update(sql, share.getUser_id(), share.getGoods_id(), share.getShare_type(), share.getShare_ip());
    }
    
    /**
     * 根据商品ID获取分享次数
     * @param goods_id 商品ID
     * @return 分享次数
     * @throws SQLException SQL异常
     */
    public int getShareCountByGoodsId(int goods_id) throws SQLException {
        QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select count(*) from share where goods_id=?";
        Number count = (Number)r.query(sql, new ScalarHandler(), goods_id);
        return count.intValue();
    }
    
    /**
     * 根据分享类型和商品ID获取分享次数
     * @param goods_id 商品ID
     * @param share_type 分享类型
     * @return 分享次数
     * @throws SQLException SQL异常
     */
    public int getShareCountByTypeAndGoodsId(int goods_id, String share_type) throws SQLException {
        QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select count(*) from share where goods_id=? and share_type=?";
        Number count = (Number)r.query(sql, new ScalarHandler(), goods_id, share_type);
        return count.intValue();
    }
    
    /**
     * 获取热门分享商品的ID列表
     * @param limit 返回的记录数量
     * @return 商品ID列表
     * @throws SQLException SQL异常
     */
    public List<Integer> getHotShareGoodsIds(int limit) throws SQLException {
        QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select goods_id from share group by goods_id order by count(*) desc limit ?";
        return r.query(sql, new BeanListHandler<Integer>(Integer.class), limit);
    }
    
    /**
     * 根据用户ID获取分享记录
     * @param user_id 用户ID
     * @return 分享记录列表
     * @throws SQLException SQL异常
     */
    public List<Share> getSharesByUserId(int user_id) throws SQLException {
        QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select * from share where user_id=? order by share_time desc";
        return r.query(sql, new BeanListHandler<Share>(Share.class), user_id);
    }
} 